package be.ipl.streams.usecasesimpl;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import be.ipl.streams.dao.PlayerDao;
import be.ipl.streams.domaine.Player;
import be.ipl.streams.exceptions.ArgumentInvalideException;
import be.ipl.streams.exceptions.LoginAlreadyExistException;
import be.ipl.streams.exceptions.LoginOrPasswordIncorrectException;
import be.ipl.streams.usecases.PlayerManagement;
import be.ipl.streams.util.Util;

@Stateless
public class PlayerManagementImpl implements PlayerManagement {
	
	@EJB
	private PlayerDao playerDao ;
	
	@Override
	public Player register(String login, String password)
			throws ArgumentInvalideException, LoginAlreadyExistException {
		Util.checkString(login);
		Util.checkString(password);
		
		List<Player> players = playerDao.list();
		for ( Player p : players ){
			if ( p.getLogin().equals(login) )
				throw new LoginAlreadyExistException();
		}
		
		Player player = new Player(login, password);
		playerDao.register(player);
		return player;
		
		/*
		Player player = playerDao.search(login);
		if ( player != null ){
			throw new LoginAlreadyExistException();
		}
		player = new Player(login, password);
		playerDao.register(player);
		
		return player ;*/
	}

	@Override
	public Player login(String login, String password)
			throws ArgumentInvalideException, LoginOrPasswordIncorrectException {
		Util.checkString(login);
		Util.checkString(password);
		
		List<Player> players = playerDao.list();
		for ( Player p : players ){
			if ( p.getLogin().equals(login) && p.getPassword().equals(password) )
				return p ;
		}
		
		throw new LoginOrPasswordIncorrectException();
		
		/*
		Player player = playerDao.search(login, password);
		if ( player == null ) throw new LoginOrPasswordIncorrectException();
		return player ;
		*/
	}

}